// 引入excel解析包
import * as XLSX from 'xlsx'
// 解析xlsx文件的方法
const parseXLSX = async (file: any) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => {
      try {
        const arrayBuffer = reader.result
        const uint8Array = new Uint8Array(arrayBuffer as ArrayBuffer)
        const workbook = XLSX.read(uint8Array, { type: 'array' })
        const sheetName = workbook.SheetNames[0]
        const worksheet = workbook.Sheets[sheetName]
        const data = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
        resolve(data)
      } catch (error) {
        reject(error)
      }
    }
    reader.readAsArrayBuffer(file)
  })
}

const checkXLSX = (data: Array<any>): boolean => {
  if (data[0].length !== 11) {
    return false
  }

  const standard = [
    '*实体业务ID',
    '*实体名称',
    '分类名称',
    '*分类码',
    '所属行政区',
    '*行政区划码',
    '区域范围说明',
    '*经度',
    '*纬度',
    '高程',
    '备注'
  ]

  for (let i = 0; i < standard.length; i++) {
    if (data[0][i] !== standard[i]) {
      return false
    }
  }

  for (let i = 1; i < data.length; i++) {
    if (data[i].length !== 0 && data[i - 1].length === 0) {
      return false
    }
  }

  return true
}

export { checkXLSX, parseXLSX }
